package com.project.personalfundmanager.server;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.project.personalfundmanager.client.GreetingService;
import com.project.personalfundmanager.shared.DAOs.TaxInfoGroupDAO;
import com.project.personalfundmanager.shared.models.TaxInfoGroupModel;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings( "serial" )
public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService
{
	public static final String INFO_FOLDER = "/WEB-INF/classes/com/project/personalfundmanager/server/info/";
	public static final String FILE_EXTENSION = ".info";
	Objectify objectify = ObjectifyService.begin();

	static
	{
		ObjectifyService.register( TaxInfoGroupDAO.class );
	}

	public Boolean saveObject( TaxInfoGroupModel model )
	{
		final TaxInfoGroupDAO taxInfoGroupDAO = new TaxInfoGroupDAO( model );
		objectify.put( taxInfoGroupDAO );
		return true;
	}

	@Override
	public TaxInfoGroupModel getObject( long uid )
	{
		TaxInfoGroupDAO dao = objectify.get( TaxInfoGroupDAO.class, uid );
		return new TaxInfoGroupModel(dao);
	}

	@Override
	public String getInfo( String fileName ) throws FileNotFoundException
	{
		ServletContext context = getServletContext();
		BufferedReader reader = new BufferedReader(new InputStreamReader(context.getResourceAsStream( INFO_FOLDER + fileName + FILE_EXTENSION)));
		StringBuilder value = new StringBuilder();
		try
		{
			String line = null;
			while ( ( line = reader.readLine() ) != null )
			{
				value.append( line + "\n" );
			}
		}
		catch ( IOException e )
		{
			e.printStackTrace();
		}
		return value.toString();
	}

	@Override
	public boolean sendMail(String value) {
		Mailer mailer = new Mailer();
		List<String> toAddresses = new ArrayList<String>();
		toAddresses.add(value);
		mailer.sendMail(toAddresses, "Tax Return file for year 2010-11", "Hi sir,\n\n\tYour text filing is completed.\n\nRegards,\nFacebook tax manager", null);
		return true;
	}
}
